//
//  RepairEditAndAddViewController.m
//  wtshoppingcite
//
//  Created by Baojia-LC on 14/11/4.
//  Copyright (c) 2014年 TW. All rights reserved.
//

#import "RepairEditAndAddViewController.h"
#import "CustomBlueTextView.h"
#import "PostPhotoView.h"
#import "PhotFacImage.h"
#import "TimeSecondPickView.h"
#import "UpYun.h"
#import "AdispatchView.h"
#import "ImgScrollView.h"
#import "PhotFacImage.h"

#define titlecolor COLOR_RGB(164, 164, 164)
@interface RepairEditAndAddViewController ()<UITextFieldDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,adispathViewDelegate,PostPhotoDelegate,ImgScrollViewDelegate,UIScrollViewDelegate>

@property(nonatomic,strong)UITextField* repairDoTextFeild;
@property(nonatomic,strong)UIButton* wishTimeButton;
@property(nonatomic,strong)CustomBlueTextView* infoTextView;
@property(nonatomic,strong)NSString *expectEndTime;
@property(nonatomic,strong)PostPhotoView* postPhotoView;
@property(nonatomic,assign)NSInteger postImgNum;

@property(nonatomic,assign)BOOL isCommit;

@property(strong,nonatomic)UIScrollView *myScrollView;
@property(strong,nonatomic)UIView *markView;
@property(strong,nonatomic)UIView *scrollPanel;
@property(strong,nonatomic)ImgScrollView *lastImgScrollView;
@property(assign,nonatomic)NSInteger currentIndex;

@end

@implementation RepairEditAndAddViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _scrollPanel = [[UIView alloc] initWithFrame:self.view.bounds];
    _scrollPanel.backgroundColor = [UIColor clearColor];
    _scrollPanel.alpha = 0;
    [self.view addSubview:_scrollPanel];
    
    _markView = [[UIView alloc] initWithFrame:_scrollPanel.bounds];
    _markView.backgroundColor = MAIN_BLACK_COLOR;
    _markView.alpha = 0.0;
    [_scrollPanel addSubview:_markView];
    
    _myScrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    [_scrollPanel addSubview:_myScrollView];
    _myScrollView.pagingEnabled = YES;
    _myScrollView.delegate = self;
    CGSize contentSize = _myScrollView.contentSize;
    contentSize.height = self.view.bounds.size.height;
    contentSize.width = 320 * 3;
    _myScrollView.contentSize = contentSize;

    
    if (_type == NSBlueViewControllerRepairStyle) {
        [self setTitleView:@"报修"];
    }else if (_type == NSBlueViewControllerComplainStyle){
        [self setTitleView:@"投诉"];
    }else if (_type == NSBlueViewControllerPraiseStyle){
        [self setTitleView:@"表扬"];
    }
    _isCommit = YES;
    [self setRightButton:@"提交" sel:@selector(commit:) viewController:self];
    [self createSubView];
}

-(void)createSubView{
    
    _imageUyArray = [[NSMutableArray alloc]initWithCapacity:1];
    
    NSString *title;
    NSString *time;
    if (_type == NSBlueViewControllerRepairStyle) {
        
        title = @"修什么?";
        time = @"期望上门时间段";
        
    }else if (_type == NSBlueViewControllerComplainStyle){
        title = @"投诉标题";
        time = @"投诉内容";
    
    }
    
    _repairDoTextFeild = [UnitToolCommonView viewLineTextFeildWithText:title textColor:COLOR_RGB(164, 164, 164) frame:CGRectMake(10, 5, kWidth-20, 30) font:[UIFont boldSystemFontOfSize:TITLESMALL_FONT]];
    _repairDoTextFeild.delegate = self;
    [self.view addSubview:_repairDoTextFeild];
    
    if (_type == NSBlueViewControllerRepairStyle) {
        
        _wishTimeButton = [UnitToolCommonView createLineButtonViewWithFrame:CGRectMake(_repairDoTextFeild.left, _repairDoTextFeild.bottom+30, kWidth-20, 30) title:time titleColor:titlecolor font:[UIFont boldSystemFontOfSize:TITLESMALL_FONT] sel:@selector(wishTimeClick:) target:self];
        [self.view addSubview:_wishTimeButton];

    }else if (_type == NSBlueViewControllerComplainStyle){
        
        _wishTimeButton = [UnitToolCommonView createLineButtonViewWithFrame:CGRectMake(_repairDoTextFeild.left, _repairDoTextFeild.bottom+30, kWidth-20, 30) title:time titleColor:titlecolor font:[UIFont boldSystemFontOfSize:TITLESMALL_FONT] sel:@selector(complaintClick:) target:self];
        [self.view addSubview:_wishTimeButton];
    }
    
    _infoTextView = [[CustomBlueTextView alloc] initWithFrame:CGRectMake(_repairDoTextFeild.left, _wishTimeButton.bottom +10, kWidth-20, 140)withPlaceHolder:@"详细描述下..."];
    [self.view addSubview:_infoTextView];
    
    _postPhotoView = [[PostPhotoView alloc] initWithFrame:CGRectMake(5, _infoTextView.bottom+10, kWidth-10, 90)];
    _postPhotoView.delegate = self;
    [self.view addSubview:_postPhotoView];
    
}

#pragma arguments 图片缩放delegate
-(void)tappedWithObject:(id)sender{
    
    [self.view bringSubviewToFront:_scrollPanel];
    _scrollPanel.alpha = 1.0;
    
    PhotFacImage *tmpView = sender;
    _currentIndex = tmpView.tag - 100;
    
    
    //转换后的rect
    CGRect convertRect = [[tmpView superview] convertRect:tmpView.frame toView:self.view];
    
    CGPoint contentOffset = _myScrollView.contentOffset;
    contentOffset.x = _currentIndex*320;
    _myScrollView.contentOffset = contentOffset;
    
    //添加
    [self addSubImgView];
    
    ImgScrollView *tmpImgScrollView = [[ImgScrollView alloc] initWithFrame:(CGRect){contentOffset,_myScrollView.bounds.size}];
    [tmpImgScrollView setContentWithFrame:convertRect];
    [tmpImgScrollView setImage:tmpView.imageView.image];
    [_myScrollView addSubview:tmpImgScrollView];
    _myScrollView.contentSize = CGSizeMake(1*SCREEN_WIDTH, SCREEN_HEIGHT);
    
    tmpImgScrollView.i_delegate = self;
    
    [self performSelector:@selector(setOriginFrame:) withObject:tmpImgScrollView afterDelay:0.1];
    
}

#pragma mark - custom method 放大
- (void) addSubImgView
{
    
    for (UIView *tmpView in _myScrollView.subviews)
    {
        [tmpView removeFromSuperview];
    }
    
    for (int i = 0; i <= 1; i ++)
    {
        if (i == _currentIndex)
        {
            continue;
        }
        
        PhotFacImage *tmpView = (PhotFacImage *)[self.view viewWithTag:100 + i];
        
        //转换后的rect
        CGRect convertRect = [[tmpView superview] convertRect:tmpView.frame toView:self.view];
        
        ImgScrollView *tmpImgScrollView = [[ImgScrollView alloc] initWithFrame:(CGRect){i*_myScrollView.bounds.size.width,0,_myScrollView.bounds.size}];
        [tmpImgScrollView setContentWithFrame:convertRect];
        [tmpImgScrollView setImage:tmpView.imageView.image];
        [_myScrollView addSubview:tmpImgScrollView];
        tmpImgScrollView.i_delegate = self;
        
        [tmpImgScrollView setAnimationRect];
    }
}


- (void) setOriginFrame:(ImgScrollView *) sender
{
    
    [UIView animateWithDuration:0.4 animations:^{
        [sender setAnimationRect];
        _markView.alpha = 1.0;
        [self.navigationController setNavigationBarHidden:YES];
    }];
}


#pragma mark 缩小
- (void) tapImageViewTappedWithObject:(id)sender
{
    [self.navigationController setNavigationBarHidden:NO];
    
    ImgScrollView *tmpImgView = sender;
    [UIView animateWithDuration:0.5 animations:^{
        _markView.alpha = 0;
        [tmpImgView rechangeInitRdct];
    } completion:^(BOOL finished) {
        _scrollPanel.alpha = 0;
    }];
    
}



//提交
-(void)commit:(UIButton*)button{
    
    if (_postPhotoView.imageArray.count == 0) {
        __weak RepairEditAndAddViewController *self_weak = self;
        [self_weak showToastMessage:@"请输入正确数据"];
        return;
    }
    
    UIImage *img =_postPhotoView.imageArray[0];
    float scale = 1000.0/img.size.width;
    img = [UIImage imageWithImageSimple:img scaledToSize:CGSizeMake(1000, img.size.height*scale)];
    img = [UIImage imageWithImageSimple:img scaledToSize:CGSizeMake(50, 50)];
    
    [_postPhotoView.imageArray insertObject:img atIndex:0];

    [self showToastMessage:@"正在加载"];
    [self uploadFile:_postPhotoView.imageArray];
      
        
    button.userInteractionEnabled = NO;
    NSLog(@"yes");
    
    //[self getRepair];
}

- (void)uploadFile:(NSArray *)imageArray {
    UpYun *uy = [[UpYun alloc] init];
    
    int i= 0;
    
    uy.successBlocker = ^(id data)
    {
        
        //      http://twshop.b0.upaiyun.com/13544047502/13544047502_1420627297_2.jpg
        
        
        NSDictionary *dic = (NSDictionary *)data;
            
        NSString *strName = [NSString stringWithFormat:@"http://%@.b0.upaiyun.com%@",DEFAULT_BUCKET,[dic objectForKey:@"url"]];
            [_imageUyArray addObject:strName];
            
        NSLog(@"imageUyArray:%@",_imageUyArray);
        NSLog(@"%@",data);
        _postImgNum++;
        
        if (_type == NSBlueViewControllerRepairStyle) {
            [self getRepair];
        }else if (_type == NSBlueViewControllerComplainStyle){
            [self getComplaint];
        }else if (_type ==NSBlueViewControllerPraiseStyle){
            [self getPraise];
        }
        
    };
    
    uy.failBlocker = ^(NSError * error)
    {
        NSString *message = [error.userInfo objectForKey:@"message"];
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"error" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        NSLog(@"%@",error);
        
        
    };
    
    _postImgNum = 0;
    
    for (UIImage *image in imageArray) {
 
    //	@brief	根据 UIImage 上传
    
        UIImage* img = image;
        if (image.size.width>1000)
        {
            float scale = 1000.0/image.size.width ;
            img = [UIImage imageWithImageSimple:image scaledToSize:CGSizeMake(1000, image.size.height*scale)];
//            img = [UIImage imageWithImageSimple:img scaledToSize:CGSizeMake(SCREEN_WIDTH-60*2, 150)];
        }
        
        [uy uploadFile:img saveKey:[self getSaveKey:i++]];
    }
    
}


-(NSString * )getSaveKey:(NSInteger)imageCount{
    /**
     *	@brief	方式1 由开发者生成saveKey
     //http://twshare.b0.upaiyun.com/18666224968/18666224968_1420530610093_s.jpg
     */
    
    NSString *imageName;
    if (imageCount == 0) {
        
        imageName = @"s";
        
    }
    else{
     
        imageName = [NSString stringWithFormat:@"%d",imageCount];
    }
    
    //NSDate *d = [NSDate date];
    
    NSString* date;
    NSString* timeNow;
    
    NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
    [formatter setDateFormat:@"YYYY_MM_dd_hh_mm_ss_SSS"];
    date = [formatter stringFromDate:[NSDate date]];
    timeNow = [[NSString alloc] initWithFormat:@"%@", date];
   
    //self.imageStr = [NSString stringWithFormat:@"/%d/%d/%.0f.jpg",[self getYear:d],[self getMonth:d],[[NSDate date] timeIntervalSince1970]];
    
    self.imageStr = [NSString stringWithFormat:@"/%@/%@_%@.jpg",[RegisterHelper shareHelper].registerPhoneNum,timeNow,imageName];
    return self.imageStr;
    
}

#pragma mark 物业报修提交
-(void)getRepair{
    NSString *userId = [RegisterHelper shareHelper].userId;
    NSString *comnityId = [RegisterHelper shareHelper].citesId;
    NSString *repairName = _repairDoTextFeild.text;
    NSString *expectedEndTime = _expectEndTime;
    NSString *descr = _infoTextView.text;
    NSArray *imgPathsArray;
    NSMutableArray *imgPaths = [NSMutableArray new];
    NSString *smallImgPath;
    
    if (_imageUyArray.count != 0) {
       imgPathsArray = _imageUyArray;
       smallImgPath = _imageUyArray[0];
    }
    
    if(_postPhotoView.imageArray.count != _postImgNum){
        return;
    }
    
    
    for (int i = 1; i<_imageUyArray.count; i++) {
        
        [imgPaths addObject:_imageUyArray[i]];
    }
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    SetValueForKey(dic, userId, @"userId");
    SetValueForKey(dic, comnityId, @"comnityId");
    SetValueForKey(dic, repairName, @"repairName");
    SetValueForKey(dic, expectedEndTime, @"expectedEndTime");
    SetValueForKey(dic, descr, @"descr");
    SetValueForKey(dic, imgPaths, @"imgPaths");
    SetValueForKey(dic, smallImgPath, @"smallImgPath");
    
    
    __weak RepairEditAndAddViewController *weak_self = self;
    
    [NetWorkService byRequestWithAPIPrefix:kBaseAppUrl
                              andAPISuffix:kRepairs
                             andHttpMethod:@"POST"
                             andParameters:dic
                           andRequestCache:NO
                            andUseParamDic:YES
                       andPostDataEncoding:MKNKPostDataEncodingTypeJSON
                     andRequestFinishBlock:^(BYRequest *request, BYResponse *response) {
                         if (response.isError) {
                             [self.hud hide:YES];

                             DLog(@"error %@",response.errorMessage);
                             
                            
                         }else{
                             
                             [self.hud hide:YES];
                             [self showToastMessage:@"上传成功"];

                             NSDictionary *responseDic = request.responseJSON;
                             DLog(@"成功数据:%@",responseDic);
                             
                             [weak_self.navigationController popViewControllerAnimated:YES];
                         }
                     }];
    
}

#pragma mark 投诉提交
-(void)getComplaint{
    
    NSString *userId = [RegisterHelper shareHelper].userId;
    NSString *comnityId = [RegisterHelper shareHelper].citesId;
    NSString *content = _infoTextView.text;
    NSString *title = _repairDoTextFeild.text;
    NSString *type = _expectEndTime;
    //分享到交流区
    NSString *isShare = @"0";
    
    
    NSArray *imgPathsArray;
    NSMutableArray *imgPaths = [NSMutableArray new];
    NSString *smallImgPath;
    
    if (_imageUyArray.count != 0) {
        imgPathsArray = _imageUyArray;
        smallImgPath = _imageUyArray[0];
    }
    
    if(_postPhotoView.imageArray.count != _postImgNum){
        return;
    }
    
    
    for (int i = 1; i<_imageUyArray.count; i++) {
        
        [imgPaths addObject:_imageUyArray[i]];
    }
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    SetValueForKey(dic, userId, @"userId");
    SetValueForKey(dic, comnityId, @"comnityId");
    SetValueForKey(dic, content, @"content");
    SetValueForKey(dic, isShare, @"isShare");
    SetValueForKey(dic, title, @"title");
    SetValueForKey(dic, imgPaths, @"imgPaths");
    SetValueForKey(dic, smallImgPath, @"smallImgPath");
    SetValueForKey(dic, type, @"type");
    
    
    __weak RepairEditAndAddViewController *weak_self = self;
    
    [NetWorkService byRequestWithAPIPrefix:kBaseAppUrl
                              andAPISuffix:kComplaintCreate
                             andHttpMethod:@"POST"
                             andParameters:dic
                           andRequestCache:NO
                            andUseParamDic:YES
                       andPostDataEncoding:MKNKPostDataEncodingTypeJSON
                     andRequestFinishBlock:^(BYRequest *request, BYResponse *response) {
                         if (response.isError) {
                             
                             DLog(@"error %@",response.errorMessage);
                             
                             
                         }else{
                             
                             [self showToastMessage:@"上传成功"];
                             
                             NSDictionary *responseDic = request.responseJSON;
                             DLog(@"成功数据:%@",responseDic);
                             
                             [weak_self.navigationController popViewControllerAnimated:YES];
                         }
                     }];
    
}




#pragma mark 表扬提交
-(void)getPraise{
    
    NSString *userId = [RegisterHelper shareHelper].userId;
    NSString *comnityId = [RegisterHelper shareHelper].citesId;
    NSString *content = _infoTextView.text;
    NSString *title = _repairDoTextFeild.text;
    //分享到交流区
    NSString *isShare = @"0";
    
    NSArray *imgPathsArray;
    NSMutableArray *imgPaths = [NSMutableArray new];
    NSString *smallImgPath;
    
    if (_imageUyArray.count != 0) {
        imgPathsArray = _imageUyArray;
        smallImgPath = _imageUyArray[0];
    }
    
    if(_postPhotoView.imageArray.count != _postImgNum){
        return;
    }
    
    
    for (int i = 1; i<_imageUyArray.count; i++) {
        
        [imgPaths addObject:_imageUyArray[i]];
    }
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    SetValueForKey(dic, userId, @"userId");
    SetValueForKey(dic, comnityId, @"comnityId");
    SetValueForKey(dic, content, @"content");
    SetValueForKey(dic, isShare, @"isShare");
    SetValueForKey(dic, title, @"title");
    SetValueForKey(dic, imgPaths, @"imgPaths");
    SetValueForKey(dic, smallImgPath, @"smallImgPath");
    
    
    __weak RepairEditAndAddViewController *weak_self = self;
    
    [NetWorkService byRequestWithAPIPrefix:kBaseAppUrl
                              andAPISuffix:kPariseCreate
                             andHttpMethod:@"POST"
                             andParameters:dic
                           andRequestCache:NO
                            andUseParamDic:YES
                       andPostDataEncoding:MKNKPostDataEncodingTypeJSON
                     andRequestFinishBlock:^(BYRequest *request, BYResponse *response) {
                         if (response.isError) {
                             
                             DLog(@"error %@",response.errorMessage);
                             
                             
                         }else{
                             
                             [self showToastMessage:@"上传成功"];
                             
                             NSDictionary *responseDic = request.responseJSON;
                             DLog(@"成功数据:%@",responseDic);
                             
                             [weak_self.navigationController popViewControllerAnimated:YES];
                         }
                     }];
    
}


//期望时间
-(void)wishTimeClick:(UIButton*)button{
    
    [_infoTextView resignFirstResponder];
    [_repairDoTextFeild resignFirstResponder];
    
    TimeSecondPickView* timePickerView = [[TimeSecondPickView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 300)];
    timePickerView.titleLabel.text = @"期望上门时间段";
    [timePickerView showView:self.view];
    [self.view addSubview:timePickerView];
    
    timePickerView.selectBlock = ^(int index,NSString* date){
        [_wishTimeButton setTitle:date forState:UIControlStateNormal];
        _expectEndTime = date;
        
    };
}

//选择投诉类型
-(void)complaintClick:(UIButton *)button{
    
    [_infoTextView resignFirstResponder];
    [_repairDoTextFeild resignFirstResponder];
    
    AdispatchView *adispatchView = [[AdispatchView alloc]initWithFrame:CGRectMake(20, 40, kWidth - 40, 44*5)];
    [adispatchView showView:self.view];
    adispatchView.delegate = self;
    adispatchView.titleArray = @[@"小区安全", @"清洁绿化",@"公共设备", @"U站服务及人员",@"App使用",@"其它"];
    [self.view addSubview:adispatchView];
    

}

#pragma mark adispatchViewDlegate
-(void)adispathView:(NSString *)title{
    
    [_wishTimeButton setTitle:title forState:UIControlStateNormal];
    if ([title isEqual:@"小区安全"]) {
        _expectEndTime = @"0";
    }else if([title isEqual:@"清洁绿化"]){
        _expectEndTime = @"1";
    }else if([title isEqual:@"公共设备"]){
        _expectEndTime = @"2";
    }else if([title isEqual:@"U站服务及人员"]){
        _expectEndTime = @"3";
    }else if([title isEqual:@"App使用"]){
        _expectEndTime = @"4";
    }else if([title isEqual:@"其它"]){
        _expectEndTime = @"5";
    }
    
}


- (int)getYear:(NSDate *) date{
    NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
    [formatter setTimeStyle:NSDateFormatterMediumStyle];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSInteger unitFlags = NSYearCalendarUnit;
    NSDateComponents *comps = [calendar components:unitFlags fromDate:date];
    int year=[comps year];
    return year;
}

- (int)getMonth:(NSDate *) date{
    NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
    [formatter setTimeStyle:NSDateFormatterMediumStyle];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSInteger unitFlags = NSMonthCalendarUnit;
    NSDateComponents *comps = [calendar components:unitFlags fromDate:date];
    int month = [comps month];
    return month;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [textField resignFirstResponder];
    
    return YES;
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
